import axios from "axios"
import config from '../config'
import { ElLoading } from "element-plus";
import useToken from "../stores/token";
import notification from '../utils/notification.js'
import router from '../router/router.js'

const baseURL = config.baseURL;
var loadingInstance = null;
const service = axios.create({ baseURL })

service.interceptors.request.use(config => {
    loadingInstance = ElLoading.service()
    const { token } = useToken();
    if (token) {
        config.headers.jwt = token
    }
    return config
})

service.interceptors.response.use(response => {
        loadingInstance.close()
        const { errno, errmsg, data } = response.data
        if (errno === 0) {
            if (errmsg !== '') {
                notification({

                    message: errmsg,
                    type: 'success',
                })
            }
            return data || true
        }
        notification({
            message: errmsg,
            type: 'error'
        })
        if (errno === 2) {
            router.push({ name: 'login' })
        }
        return false
    },
    error => {
        loadingInstance.close();
        notification({
            message: '请求失败',
            type: 'error'
        })
        console.log(error)
    })

export default service;